<?php
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport('joomla.application.component.model');

class igbaseModel extends JModel
{
	protected $_data = null;
	protected $_total = null;
	protected $_pagination = null;
	
	function __construct()
	{
		parent::__construct();
        global $mainframe, $option;
        
        $limit		= $mainframe->getUserStateFromRequest( $this->context.'.limit', 'limit', $mainframe->getCfg('list_limit'), 'int' );
		$limitstart	= $mainframe->getUserStateFromRequest( $this->context.'.limitstart', 'limitstart', 0, 'int' );
		
		$limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);
		
		$this->setState('limit', $limit);
		$this->setState('limitstart', $limitstart);
		
		$cid = JRequest::getVar('cid', array(0), '', 'array');
		$catid = JRequest::getInt('catid',0);
        
		$this->setId($cid[0], $catid);
    }
    
    function setId($id, $catid)
	{
		$this->_id = (int)$id;
		$this->_catid = (int)$catid;
	}
    
    function getData()
	{
		if (empty($this->_data))
		{
			$query = $this->_buildQuery();
			$this->_data = $this->_getList($query, $this->getState('limitstart'), $this->getState('limit'));
		}
		return $this->_data;
	}
	
	function getTotal()
	{
		if (empty($this->_total))
		{
			$query = $this->_buildQuery();
			$this->_total = $this->_getListCount($query);
		}

		return $this->_total;
	}
	
	function getPagination()
	{
		if (empty($this->_pagination))
		{
			jimport('joomla.html.pagination');
			$this->_pagination = new JPagination( $this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
		}

		return $this->_pagination;
	}
	
	function _buildContentOrderBy()
	{
		global $mainframe, $option;
		$filter_order		= $mainframe->getUserStateFromRequest( $this->context.'.filter_order',		'filter_order',		$this->filterOrderDefault,	'cmd' );
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( $this->context.'.filter_order_Dir',	'filter_order_Dir',	'',				'word' );
		$orderby 	= ' ORDER BY '.$filter_order.' '.$filter_order_Dir;
	
		return $orderby;
	}
	
	function getCategory($id)
	{
		$query = 'SELECT * FROM #__igallery WHERE id = '. (int)$id;
		$this->_db->setQuery($query);
		$this->_category = $this->_db->loadObject();
	    return $this->_category;
    }
    
    function getProfile($id)
	{
		$query = 'SELECT * FROM #__igallery_profiles WHERE id = '. (int)$id;
		$this->_db->setQuery($query);
		$this->_profile = $this->_db->loadObject();
	    return $this->_profile;
    }
    
    function getPhoto($id)
	{
		$query = 'SELECT * FROM #__igallery_img WHERE id = '. (int)$id;
		$this->_db->setQuery($query);
		$this->_photo = $this->_db->loadObject();
		return $this->_photo;
	}
    
    function remove()
	{
	    $cid = JRequest::getVar( 'cid', array(), '', 'array' );
		JArrayHelper::toInteger($cid);
		
		if (count( $cid ))
		{
			$cids = implode( ',', $cid );
			$query = 'DELETE FROM #__'.$this->tablename.' WHERE id IN ( '.$cids.' )';
			$this->_db->setQuery( $query );
			if(!$this->_db->query()) 
			{
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
		}
        return true;
	}
	
	function publish($publish)
	{
	    $cid = JRequest::getVar( 'cid', array(), '', 'array' );
		JArrayHelper::toInteger($cid);
		
		if (count($cid))
		{
			$cids = implode( ',', $cid );

			$query = 'UPDATE #__'.$this->tablename.' SET published = '.(int)$publish
				. ' WHERE id IN ( '.$cids.' )';
			$this->_db->setQuery( $query );
			if (!$this->_db->query()) 
			{
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
		}

		return true;
	}
	
	function moderate($moderate)
	{
	    $cid = JRequest::getVar( 'cid', array(), '', 'array' );
		JArrayHelper::toInteger($cid);
		
		if (count($cid))
		{
			$cids = implode( ',', $cid );

			$query = 'UPDATE #__'.$this->tablename.' SET moderate = '.(int)$moderate
				. ' WHERE id IN ( '.$cids.' )';
			$this->_db->setQuery( $query );
			if (!$this->_db->query()) 
			{
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
		}

		return true;
	}
	
	function move($direction)
	{
		$row =& $this->getTable($this->tablename);
		if (!$row->load($this->_id)) 
		{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		if (!$row->move($direction) ) 
		{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		return true;
	}

	function saveorder()
	{
	    $cid 	= JRequest::getVar( 'cid', array(), '', 'array' );
		$order 	= JRequest::getVar( 'order', array(), '', 'array' );
		JArrayHelper::toInteger($cid);
		JArrayHelper::toInteger($order);
		
		$row =& $this->getTable($this->tablename);

		for( $i=0; $i < count($cid); $i++ )
		{
			$row->load( (int) $cid[$i] );

			if ($row->ordering != $order[$i])
			{
				$row->ordering = $order[$i];
				if (!$row->store()) 
				{
					$this->setError($this->_db->getErrorMsg());
					return false;
				}
			}
		}
		
		$row->reorder($this->reorderClause);

		return true;
	}
	
	function authenticate($aclColumn='', $id='', $bounceGuest=true, $checkConfigEnabled = true)
	{
		$user =& JFactory::getUser();
		$db	=& JFactory::getDBO();
		$configArray =& JComponentHelper::getParams('com_igallery');
		
		$allowFrontend = $configArray->get('allow_frontend_creation', 0);
		if($allowFrontend != 1 && $checkConfigEnabled)
		{
			echo JText::_('PLEASE ENABLE FRONTEND');
			return false;
		}
		
		if( $user->get('guest') &&  $bounceGuest == true)
		{
			echo JText::_('PLEASE LOGIN TO VIEW');
			return false;
		}
		
		if(empty($aclColumn) && empty($id))
		{
			return true;
		}
		
		$table = preg_match("/photo/i", $aclColumn) ? 'igallery_img' : 'igallery';
		
	    if($table == 'igallery')
		{
			$query = 'SELECT '.
			'#__igallery.id, #__igallery.user, '.
			'#__igallery_profiles.'.$db->getEscaped($aclColumn).' '.
			'FROM #__igallery '.
			'INNER JOIN #__igallery_profiles ON #__igallery_profiles.id = #__igallery.profile '.
			'WHERE #__igallery.id = '.(int)$id;
		}
		else
		{
			$query = 'SELECT '.
			'#__igallery_img.id, #__igallery_img.user, '.
			'#__igallery.name, '.
			'#__igallery_profiles.'.$db->getEscaped($aclColumn).' '.
			'FROM #__igallery_img '.
			'INNER JOIN #__igallery ON #__igallery.id = #__igallery_img.gallery_id '.
			'INNER JOIN #__igallery_profiles ON #__igallery_profiles.id = #__igallery.profile '.
			'WHERE #__igallery_img.id = '.(int)$id;
		}
		
		$db->setQuery($query);
        $row = $db->loadObject();
        
        $gid = $user->get('gid', 18);
        $aclValuesArray = explode(',', $row->{$aclColumn});
        $accessOk = false;
        
        if($gid == '23' || $gid == '24' || $gid == '25')
        {
        	return true;
        }
        
        for($i=0; $i<count($aclValuesArray); $i++)
        {
        	if($aclValuesArray[$i] == 0) 
	        {
			    $accessOk = false;
			    break;
		    }
		    
        	if($aclValuesArray[$i] == 2) 
	        {
			    $accessOk = true;
			    break;
		    }
	        
	        if($aclValuesArray[$i] == 1) 
	        {
			    if($user->id == $row->user)
		        {
		        	$accessOk = true;
			    	break;
		        }
			}
			
			if($aclValuesArray[$i] == $gid) 
	        {
			    $accessOk = true;
			    break;
			}
			
			if($aclValuesArray[$i] == $user->id) 
	        {
			    $accessOk = true;
			    break;
			}
			
        }
		
		return $accessOk;
	}
	
	function notify($type, $id, $text='')
	{
		$user =& JFactory::getUser();
		$db	=& JFactory::getDBO();
		
		$siteConfig =& JFactory::getConfig();
		$from = $siteConfig->getValue( 'config.mailfrom' );
		$fromname = $siteConfig->getValue( 'config.fromname' );
		
		$igalleryConfig =& JComponentHelper::getParams('com_igallery');
		$recipient = explode(',', $igalleryConfig->get('notify_emails', '') );
		
		if($type == 'comment')
		{
			$query = 'SELECT '.
			'#__igallery_img.filename, #__igallery_img.ordering, '.
			'#__igallery.name, #__igallery.id '.
			'FROM #__igallery_img '.
			'INNER JOIN #__igallery ON #__igallery.id = #__igallery_img.gallery_id '.
			'WHERE #__igallery_img.id = '. (int)$id;
			$db->setQuery($query);
			$photo = $db->loadObject();
			
			$subject = $siteConfig->getValue( 'config.sitename' ).' : '.JText::_('NEW COMMENT ADDED');
			
			$body = 
			JText::_('COMMENT').': '.$text." \n\n ".
			JText::_('USERNAME').': '.$user->name." \n\n ".
			IG_HOST.'administrator/index.php?option=com_igallery&controller=igcomment'." \n\n ".
			IG_HOST.'index.php?option=com_igallery&view=igcategory&id='.$photo->id.'&image='.$photo->ordering;
			
		}
		
		if($type == 'category')
		{
			$query = 'SELECT * from #__igallery WHERE id = '.(int)$id;
			$db->setQuery($query);
			$category = $db->loadObject();
			
			$subject = $siteConfig->getValue( 'config.sitename' ).' : '.JText::_('NEW CATEGORY ADDED');
			
			$body   = 
			JText::_('USERNAME').': '.$user->name." \n\n ".
			JText::_('CATEGORY').': '.$category->name." \n\n ".
			IG_HOST.'administrator/index.php?option=com_igallery&view=add_edit_category&cid[]='.$id." \n\n ".
			IG_HOST.'index.php?option=com_igallery&view=igcategory&id='.$id;
			
		}
		
		if($type == 'image')
		{
			$query = 'SELECT '.
			'#__igallery_img.filename, #__igallery_img.ordering, '.
			'#__igallery.name, #__igallery.id '.
			'FROM #__igallery_img '.
			'INNER JOIN #__igallery ON #__igallery.id = #__igallery_img.gallery_id '.
			'WHERE #__igallery_img.id = '. (int)$id;
			$db->setQuery($query);
			$photo = $db->loadObject();
			
			$subject = $siteConfig->getValue( 'config.sitename' ).' : '.JText::_('NEW IMAGES ADDED');
			
			$body =
			JText::_('USERNAME').': '.$user->name." \n\n ".
			JText::_('CATEGORY').': '.$photo->name." \n\n ".
			IG_HOST.'index.php?option=com_igallery&view=igcategory&id='.$photo->id;
		}
		
		if($type == 'report')
		{
			$query = 'SELECT '.
			'#__igallery_img.filename, #__igallery_img.ordering, '.
			'#__igallery.name, #__igallery.id '.
			'FROM #__igallery_img '.
			'INNER JOIN #__igallery ON #__igallery.id = #__igallery_img.gallery_id '.
			'WHERE #__igallery_img.id = '. (int)$id;
			$db->setQuery($query);
			$photo = $db->loadObject();
			
			$subject = $siteConfig->getValue('config.sitename').' : '.JText::_('IMAGE REPORTED');
			
			if( $user->get('guest') )
			{
				$user->name = JText::_('GUEST');
			}
			
			$body =
			JText::_('USERNAME').': '.$user->name." \n\n ".
			JText::_('CATEGORY').': '.$photo->name." \n\n ".
			IG_HOST.'index.php?option=com_igallery&view=igcategory&id='.$photo->id.'&image='.$photo->ordering." \n\n ".
			$text;
		}
		
		for($i=0; $i<count($recipient); $i++)
		{
			JUtility::sendMail($from, $fromname, $recipient[$i], $subject, $body);
			
			if($i > 5)
			{
				break;
			}
		}

	}

}